import axios from 'axios'
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user'

const request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000,
})

request.interceptors.request.use((config) => {
  const useStore = useUserStore()
  if (useStore.token) {
    config.headers.token = useStore.token
  }
  return config
})

request.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    let message = ''
    const status = error.response.status
    switch (status) {
      case 401:
        message = 'token expired'
        break
      case 403:
        message = 'authriator failed'
        break
      case 404:
        message = 'request cannot found'
        break
      case 500:
        message = 'server side error'
        break
      default:
        message = 'other errors'
        break
    }
    ElMessage({
      type: 'error',
      message,
    })

    return Promise.reject(error)
  },
)

export default request
